// script.js
document.addEventListener('DOMContentLoaded', function() {
    // 删除确认
    const deleteLinks = document.querySelectorAll('.delete-book');
    if (deleteLinks) {
        deleteLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                if (!confirm('确定要删除这本书吗？此操作不可恢复。')) {
                    e.preventDefault();
                }
            });
        });
    }

    // 表单验证
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            if (!username || !password) {
                e.preventDefault();
                document.getElementById('error-message').textContent = '用户名和密码不能为空';
            }
        });
    }

    const registerForm = document.getElementById('registerForm');
    if (registerForm) {
        registerForm.addEventListener('submit', function(e) {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const email = document.getElementById('email').value;

            if (!username || !password) {
                e.preventDefault();
                document.getElementById('error-message').textContent = '用户名和密码不能为空';
                return;
            }

            if (password.length < 6) {
                e.preventDefault();
                document.getElementById('error-message').textContent = '密码长度至少为6位';
                return;
            }

            if (email && !validateEmail(email)) {
                e.preventDefault();
                document.getElementById('error-message').textContent = '请输入有效的电子邮件地址';
            }
        });
    }

    const bookForm = document.getElementById('bookForm');
    if (bookForm) {
        bookForm.addEventListener('submit', function(e) {
            const title = document.getElementById('title').value;
            const author = document.getElementById('author').value;

            if (!title || !author) {
                e.preventDefault();
                document.getElementById('error-message').textContent = '书名和作者不能为空';
            }
        });
    }
});

// 邮箱验证函数
function validateEmail(email) {
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}